package com.citywithincity.redis.models;

import java.util.Collections;
import java.util.List;
import java.util.Set;

import com.citywithincity.db.Page;
import com.citywithincity.interfaces.IDestroyable;
import com.citywithincity.redis.utils.RedisUtil;

import redis.clients.jedis.Jedis;

public class RedisZSetModel<T> extends RedisZSetKeys implements IDestroyable {

	private RedisObjectModel<T> objectModel;
	
	
	public RedisZSetModel(RedisObjectModel<T> model,String zsetKey) {
		super(zsetKey);
		objectModel = model;
	}
	



	@SuppressWarnings("unchecked")
	public List<T> getRList(int count){
		Jedis jedis = null;
		try{
			jedis = RedisUtil.read();
			Set<String> set = jedis.zrevrange(getKey(),0, count);
			if(set.size()==0){
				return Collections.EMPTY_LIST;
			}
			return objectModel.getList(jedis, set);
		}finally{
			if(jedis!=null)jedis.close();
		}
	}
	
	
	@SuppressWarnings("unchecked")
	public List<T> getList(){
		Jedis jedis = null;
		try{
			jedis = RedisUtil.read();
			Set<String> set = jedis.zrange(getKey(),0, -1);
			if(set.size()==0){
				return Collections.EMPTY_LIST;
			}
			return objectModel.getList(jedis, set);
		}finally{
			if(jedis!=null)jedis.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public Page<T> getPosition(int position,int pageSize){
		Jedis jedis = null;
		try{
			jedis = RedisUtil.read();
			int count = (int)(long)jedis.zcard(getKey());
			if(count==0){
				return Page.EMPTY_PAGE;
			}
			Page<T> result = new Page<T>();
			//最大下表为count-1
			int maxIndex = position + pageSize;
			if(maxIndex > count){
				maxIndex = count;
			}
			Set<String> set = jedis.zrange(getKey(),position, maxIndex-1);
			int page = position / pageSize + 1;
			int total;
			if(count%pageSize==0){
				total = count / pageSize;
			}else{
				total = count / pageSize + 1;
			}
			List<T> list = objectModel.getList(jedis,set);
			result.setPage(page);
			result.setPageSize(pageSize);
			result.setTotalPages(total);
			result.setTotalRows(count);
			result.setList(list);
			return result;
		}finally{
			if(jedis!=null)jedis.close();
		}
	}

	@Override
	public void destroy() {
	
		objectModel = null;
	}
}
